<template>
  <div>
    <!-- <n-button size="medium" @click="changePassword = true">修改登录密码</n-button> -->
    <n-modal :show="changePassword">
      <n-card style="width: 500px" title="修改密码" size="medium" role="dialog" aria-modal="true">
        <n-alert title="提示" type="warning"
          >您的登录密码目前为原始密码，为了安全起见，请修改您的密码，密码为8-12位并且由数字和字母大小写组成</n-alert
        >
        <n-form
          :label-width="80"
          :model="passwordInfo"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="1" :x-gap="28">
            <n-gi span="1" style="margin-bottom: 20px; margin-top: 20px">
              <n-form-item label="原始密码" path="password">
                <n-input
                  placeholder="请输入原始密码"
                  v-model:value="passwordInfo.password"
                  maxlength="30"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1" style="margin-bottom: 20px">
              <n-form-item label="新密码" path="newPassword">
                <n-input
                  placeholder="请输入新密码"
                  v-model:value="passwordInfo.newPassword"
                  maxlength="30"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1" style="margin-bottom: 20px">
              <n-form-item label="确认密码" path="confirmPassword" maxlength="30">
                <n-input
                  placeholder="请确认输入密码"
                  v-model:value="passwordInfo.confirmPassword"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="addConfirm">确定</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang='ts' setup>
import { updatePassword } from '@/api/merchantPassword/updatePassword';
import { ref } from 'vue';
import { useMessage } from 'naive-ui';
import { func } from 'vue-types';
import { createStorage } from '@/utils/Storage';
import md5 from 'js-md5';

const Storage = createStorage({ storage: localStorage });

const formRef = ref(null);
const formBtnLoading = ref(false);
const changePassword = ref(false); // 是否显示模态框

const newPassword = ref(); //密码
const confirmPassword = ref(); //确认密码
console.log(newPassword);
console.log(confirmPassword);

const passwordInfo = ref({
  password: '',
  newPassword: '',
});

// 判断第二次密码与第一次是否一样（输入过程中判断）
function validatePasswordStartWith(rule, value) {
  return (
    passwordInfo.value.newPassword &&
    passwordInfo.value.newPassword.startsWith(value) &&
    passwordInfo.value.newPassword.length >= value.length
  );
}

// 判断第二次密码与第一次是否一样（失去焦点判断）
function validatePasswordSame(rule, value) {
  return value === passwordInfo.value.newPassword;
}

const model = passwordInfo;
const message = useMessage();

// 表单验证规则
const rules = {
  password: [
    {
      required: true,
      message: '请输入原始密码',
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入新密码');
        } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,12}$/.test(value)) {
          return new Error('密码为8-12位并且由数字和字母大小写组成');
        } else {
          return true;
        }
      },
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur'],
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input',
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'newPassword-input'],
    },
  ],
};

// 修改登录密码
const addConfirm = async (e) => {
  formRef.value.validate(async (errors) => {
    let userId = Storage.get('userId');
    let password = md5(passwordInfo.value.password);
    let newPassword = md5(passwordInfo.value.newPassword);
    if (!errors) {
      const data = await updatePassword({ userId, password, newPassword }).then((res) => {
        console.log(res);
        message.success('修改密码成功');
      });
      changePassword.value = false;
    } else {
      message.error('操作失败请重试');
    }
  });
};
</script>